package com.xmindguoguo.boot.modular.system.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.xmindguoguo.boot.common.annotation.OperationLog;
import com.xmindguoguo.boot.common.constant.GlobalConstant;
import com.xmindguoguo.boot.common.enumtype.OperationLogType;
import com.xmindguoguo.boot.core.BaseController;
import com.xmindguoguo.boot.core.shiro.ShiroKit;
import com.xmindguoguo.boot.modular.system.model.TSystemDeptModel;
import com.xmindguoguo.boot.modular.system.model.TSystemMenuModel;
import com.xmindguoguo.boot.modular.system.model.TSystemRelationModel;
import com.xmindguoguo.boot.modular.system.model.TSystemRoleModel;
import com.xmindguoguo.boot.modular.system.service.ITSystemDeptService;
import com.xmindguoguo.boot.modular.system.service.ITSystemMenuService;
import com.xmindguoguo.boot.modular.system.service.ITSystemRelationService;
import com.xmindguoguo.boot.modular.system.service.ITSystemRoleService;
import com.xmindguoguo.boot.util.CmUtil;
import com.xmindguoguo.boot.util.ConvertUtil;
import com.xmindguoguo.boot.util.json.JsonResult;

/**
 * 控制器 //先暂时全部小写，后面写个方法注册进来，调整大小写
 * 
 * @author xmind-果果
 * @Date 2018-12-22 22:53
 */

@Controller
@RequestMapping("/tSystemRole")
public class TSystemRoleController extends BaseController {

    // 所属子模块名称+当前功能名称
    private String PREFIX = "/system/tSystemRole/";

    @Autowired
    private ITSystemRoleService systemRoleService;
    @Autowired
    public ITSystemDeptService systemDeptService;
    @Autowired
    private ITSystemMenuService systemMenuService;
    @Autowired
    private ITSystemRelationService systemRelationService;

    /**
     * 跳转列表页
     */
    @RequestMapping("toTSystemRoleList")
    public String toTSystemRoleList() {
        return PREFIX + "tSystemRoleList";
    }

    /**
     * 查询列表数据 tree 数据时用，不用删除
     */
    @RequestMapping("tSystemRoleList")
    @ResponseBody
    public Object tSystemRoleList(TSystemRoleModel model) {
        Wrapper<TSystemRoleModel> wrapper = new EntityWrapper<>();
        /* if (ToolUtil.isNotEmpty(model.getAccount())) {
            wrapper.like("account", model.getAccount());
        }
        */
        wrapper.ne("status", GlobalConstant.MODEL_DEL);
        wrapper.orderBy("createTime", false);
        return JsonResult.sendOk(systemRoleService.selectList(wrapper)); // 跳转到列表页
    }

    @RequestMapping("toTSystemRoleAdd")
    public String toTSystemRoleAdd() {
        return PREFIX + "tSystemRoleAdd";
    }

    /**
     * 添加model
     */
    @OperationLog(logName = "添加角色", operationLogType = OperationLogType.INSERT)
    @RequestMapping("tSystemRoleAdd")
    @ResponseBody
    public Object tSystemRoleAdd(@Validated TSystemRoleModel model, BindingResult result) {
        if (result.hasErrors()) {
            return sendValidatedMsg(result);
        }
        model.setId(CmUtil.getPkId());
        model.setStatus(GlobalConstant.MODEL_ADD);
        model.setCreateTime(new Date());
        model.setCreateUserId(ShiroKit.getUserId());
        if (model.getPId() == null) {
            model.setPId(0L);
            model.setPIds(model.getId() + "");
        }
        if (model.getPId() != 0L) {
            TSystemRoleModel oldModel = systemRoleService.selectById(model.getPId());
            model.setPIds(oldModel.getPIds() + "_" + model.getId());
        }
        boolean flag = systemRoleService.insert(model);
        return flag ? JsonResult.sendOk("添加成功", null) : JsonResult.sendError("添加失败", null);
    }

    @RequestMapping("toTSystemRoleUpdate")
    public String toTSystemRoleUpdate(Long id) {
        TSystemRoleModel model = systemRoleService.selectById(id);
        request.setAttribute("model", model);
        // 查询出来对应的上级角色名称
        if (model != null && model.getPId() != 0) {
            TSystemRoleModel pModel = systemRoleService.selectById(model.getPId());
            request.setAttribute("showNameDom", pModel.getName());
        } else {
            request.setAttribute("showNameDom", "顶级");
        }
        // 查询出来对应的上级部门名称
        if (model != null && model.getPId() != 0) {
            TSystemDeptModel pModel = systemDeptService.selectById(model.getPId());
            request.setAttribute("showNameDept", pModel.getFullName());
        } else {
            request.setAttribute("showNameDept", "顶级");
        }
        return PREFIX + "tSystemRoleUpdate";
    }

    /**
     * 更新model
     */
    @OperationLog(logName = "更新角色", operationLogType = OperationLogType.UPDATE)
    @RequestMapping("tSystemRoleUpdate")
    @ResponseBody
    public Object tSystemRoleUpdate(@Validated TSystemRoleModel model, BindingResult result) {
        if (result.hasErrors()) {
            return sendValidatedMsg(result);
        }
        model.setUpdateTime(new Date());
        model.setUpdateUserId(ShiroKit.getUserId());
        if (model.getPId() == null) {
            model.setPId(0L);
            model.setPIds(model.getId() + "");
        }
        if (model.getPId() != 0L) {
            TSystemRoleModel oldModel = systemRoleService.selectById(model.getPId());
            model.setPIds(oldModel.getPIds() + "_" + model.getId());
        }
        boolean flag = systemRoleService.updateById(model);
        return flag ? JsonResult.sendOk("更新成功", null) : JsonResult.sendError("更新失败", null);
    }

    @OperationLog(logName = "删除角色", operationLogType = OperationLogType.DELETE)
    @RequestMapping("tSystemRoleDelete")
    @ResponseBody
    public Object tSystemRoleDelete(Long id) {
        TSystemRoleModel model = new TSystemRoleModel();
        model.setStatus(GlobalConstant.MODEL_DEL);
        model.setId(id);
        boolean flag = systemRoleService.updateById(model);
        return flag ? JsonResult.sendOk("删除成功", null) : JsonResult.sendError("删除失败", null);
    }

    @OperationLog(logName = "批量删除角色", operationLogType = OperationLogType.DELETE)
    @RequestMapping("tSystemRoleBatchDel")
    @ResponseBody
    public Object tSystemRoleBatchDel(String ids) {
        Long[] idsArray = ConvertUtil.StringToLongArray(ids);

        List<TSystemRoleModel> list = new ArrayList<>();
        TSystemRoleModel model = null;
        for (Long id : idsArray) {
            model = new TSystemRoleModel();
            model.setStatus(GlobalConstant.MODEL_DEL);
            model.setId(id);
            list.add(model);
        }
        boolean flag = systemRoleService.updateBatchById(list);
        return flag ? JsonResult.sendOk("删除成功", null) : JsonResult.sendError("删除失败", null);
    }

    /**
     * 跳转权限列表树
     */
    @RequestMapping("toMenu")
    public String toMenu() {
        setAttr();
        return PREFIX + "menuTree";
    }

    /**
     * 查询权限树
     * 
     * @Title tSystemMenuList
     * @author 于国帅
     * @date 2018年12月26日 下午10:50:39
     * @param model
     * @return Object
     */
    @RequestMapping("menuList")
    @ResponseBody
    public Object menuList(@RequestParam(value = "roleId", required = false) Long roleId) {
        setAttr();
        // 先查询所有的菜单
        Wrapper<TSystemMenuModel> wrapper = new EntityWrapper<>();
        wrapper.ne("status", GlobalConstant.MODEL_DEL);
        wrapper.orderBy("orderNum ", false);
        wrapper.orderBy("createTime ", false);
        List<TSystemMenuModel> menuList = systemMenuService.selectList(wrapper);
        // 根据id 查询出来所有的 已经选中的权限
        if (roleId != null) {
            Wrapper<TSystemRelationModel> relationWrapper = new EntityWrapper<>();
            relationWrapper.eq("roleId", roleId);
            List<TSystemRelationModel> relationList = systemRelationService.selectList(relationWrapper);
            if (CollectionUtils.isNotEmpty(relationList) && CollectionUtils.isNotEmpty(menuList)) {
                // 把已经选中的
                for (TSystemRelationModel tSystemRelationModel : relationList) {
                    for (TSystemMenuModel menuModel : menuList) {
                        if (menuModel.getId().equals(tSystemRelationModel.getMenId())) {
                            menuModel.setChecked(true);
                        }
                    }
                }
            }
        }
        return JsonResult.sendOk(menuList);
    }

    /**
     * 保存分配的权限
     * 
     * @Title saveMenuList
     * @author 于国帅
     * @date 2018年12月26日 下午10:54:22
     * @param model
     * @return Object systemMenuService
     */
    @OperationLog(logName = "分配角色", operationLogType = OperationLogType.OTHER)
    @RequestMapping("saveMenuList")
    @ResponseBody
//    @Transactional(propagation = Propagation.NESTED) // 比较复杂一点的事务，如果出现了异常会回滚后提交，数据库没有数据
    public Object saveMenuList(String ids, Long roleId) {
        return systemRelationService.saveMenuList(ids, roleId) ? JsonResult.sendOk("权限分配成功") : JsonResult.sendError("分配失败");
    }

}